/**
 * AI应用生成器 - 主控制器
 * 基于 Claude Agent SDK WebSocket 实时对话和预览系统
 */

class AIGenerator {
    constructor() {
        this.ws = null;
        this.reconnectTimer = null;
        this.isConnecting = false;
        this.messageQueue = [];
        this.currentCode = {
            html: '',
            css: '',
            js: ''
        };
        this.config = {
            wsUrl: localStorage.getItem('wsUrl') || 'ws://106.55.60.21:8000/ws',
            autoReconnect: localStorage.getItem('autoReconnect') !== 'false',
            reconnectInterval: parseInt(localStorage.getItem('reconnectInterval')) || 5000,
            uniappHomeUrl: 'http://106.55.60.21:3004/#/'
        };
        
        // 流式输出缓冲区
        this.streamBuffer = '';
        this.streamTimer = null;
        this.isStreaming = false;
        
        this.init();
    }

    init() {
        this.bindEvents();
        this.initSidebar();
        this.initResizer();
        this.loadDefaultPreview();
        this.autoConnect();
    }
    
    loadDefaultPreview() {
        // 移除empty-preview提示
        $('.empty-preview').fadeOut(300, function() { $(this).remove(); });
        
        // 创建手机外框
        const $phoneFrame = $('<div>', { class: 'phone-frame' });
        const $phoneScreen = $('<div>', { class: 'phone-screen' });
        
        const iframe = $('<iframe>', {
            class: 'preview-iframe',
            sandbox: 'allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-top-navigation',
            frameborder: '0',
            css: {
                width: '100%',
                height: '100%',
                border: 'none',
                display: 'block',
                background: 'white'
            }
        });
        
        // 添加加载事件监听
        iframe.on('load', () => {
            console.log('Uniapp首页加载成功');
            this.addSystemMessage('✅ Uniapp首页加载完成');
        });
        
        iframe.on('error', () => {
            console.error('Uniapp首页加载失败');
            this.addSystemMessage('❌ Uniapp首页加载失败，请检查网络连接');
        });
        
        iframe.attr('src', this.config.uniappHomeUrl);
        
        // 组装手机框架结构
        $phoneScreen.append(iframe);
        $phoneFrame.append($phoneScreen);
        
        // 清空容器并添加手机框架
        const $container = $('#previewContainer');
        $container.empty().append($phoneFrame);
        
        // 添加加载提示
        this.addSystemMessage('🔄 正在加载uniapp首页预览：' + this.config.uniappHomeUrl);
    }
    
    initSidebar() {
        $('.nav-parent').on('click', function() {
            $(this).closest('.nav-section').toggleClass('collapsed');
        });
    }

    // 绑定所有事件
    bindEvents() {
        // 发送消息
        $('#sendBtn').on('click', () => this.sendMessage());
        $('#messageInput').on('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });
        $('#messageInput').on('input', (e) => {
            this.autoResizeTextarea(e.target);
            this.updateSendButton();
        });

        // 示例提示词
        $('.example-btn').on('click', (e) => {
            const prompt = $(e.currentTarget).data('prompt');
            $('#messageInput').val(prompt);
            this.updateSendButton();
            this.sendMessage();
        });

        // 清空对话
        $('#clearBtn').on('click', () => this.clearChat());

        // 设置面板
        $('#settingsBtn').on('click', () => this.openSettings());
        $('#closeSettingsBtn, #settingsOverlay, #cancelSettingsBtn').on('click', () => this.closeSettings());
        $('#saveSettingsBtn').on('click', () => this.saveSettings());

        // 导出功能
        $('#exportChatBtn').on('click', () => this.exportChat());
        $('#exportCodeBtn').on('click', () => this.exportCode());
        $('#copyCodeBtn').on('click', () => this.copyCode());

        // 视图切换
        $('.view-btn').on('click', (e) => this.switchViewMode(e.currentTarget));
        $('.device-btn').on('click', (e) => this.switchDevice(e.currentTarget));
        $('.code-tab').on('click', (e) => this.switchCodeTab(e.currentTarget));

        // 阻止模态框内容点击冒泡
        $('.modal-content').on('click', (e) => e.stopPropagation());
    }

    // WebSocket 连接管理
    autoConnect() {
        if (this.config.autoReconnect) {
            this.connect();
        } else {
            this.updateConnectionStatus('disconnected', '未连接');
        }
    }

    connect() {
        if (this.isConnecting || (this.ws && this.ws.readyState === WebSocket.OPEN)) {
            return;
        }

        this.isConnecting = true;
        this.updateConnectionStatus('connecting', '连接中...');

        try {
            this.ws = new WebSocket(this.config.wsUrl);
            
            this.ws.onopen = () => {
                this.isConnecting = false;
                this.updateConnectionStatus('connected', '已连接');
                this.addSystemMessage('✅ WebSocket 连接成功');
                this.processPendingMessages();
            };

            this.ws.onmessage = (event) => {
                this.handleMessage(event.data);
            };

            this.ws.onerror = () => {
                this.isConnecting = false;
                this.updateConnectionStatus('error', '连接错误');
                this.addSystemMessage('⚠️ WebSocket 连接错误');
            };

            this.ws.onclose = () => {
                this.isConnecting = false;
                this.updateConnectionStatus('disconnected', '连接断开');
                this.addSystemMessage('❌ 连接断开');
                
                if (this.config.autoReconnect) {
                    this.scheduleReconnect();
                }
            };
        } catch (error) {
            this.isConnecting = false;
            this.updateConnectionStatus('error', '连接失败');
            this.addSystemMessage(`❌ 连接失败: ${error.message}`);
        }
    }

    scheduleReconnect() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
        }
        
        this.addSystemMessage(`🔄 将在 ${this.config.reconnectInterval / 1000} 秒后重连...`);
        this.reconnectTimer = setTimeout(() => {
            this.connect();
        }, this.config.reconnectInterval);
    }

    disconnect() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
        }
        
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
    }

    updateConnectionStatus(status, text) {
        const $status = $('#wsStatus');
        const $dot = $status.find('.status-dot');
        const $text = $status.find('.status-text');
        
        $dot.removeClass('status-connected status-connecting status-disconnected status-error');
        $dot.addClass(`status-${status}`);
        $text.text(text);
    }

    // 消息处理
    sendMessage() {
        const userMessage = $('#messageInput').val().trim();
        if (!userMessage) return;

        this.addUserMessage(userMessage);
        $('#messageInput').val('').trigger('input');

        // 重置流式输出状态
        this.resetStreamState();
        
        // 在用户消息前添加系统prompt，强调uniapp单页应用要求
        const systemPrompt = '';
        const fullMessage = systemPrompt + userMessage;

        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(fullMessage);
            this.addAssistantMessage('', true); // 添加加载状态
        } else {
            this.messageQueue.push(fullMessage);
            this.addSystemMessage('⏳ 消息已加入队列，等待连接...');
            if (this.config.autoReconnect) {
                this.connect();
            }
        }
    }
    
    resetStreamState() {
        // 如果正在流式输出，先结束
        if (this.isStreaming) {
            this.finishStreaming();
        }
        
        // 重置状态
        this.streamBuffer = '';
        this.isStreaming = false;
        
        if (this.streamTimer) {
            clearTimeout(this.streamTimer);
            this.streamTimer = null;
        }
    }

    processPendingMessages() {
        while (this.messageQueue.length > 0) {
            const message = this.messageQueue.shift();
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                this.ws.send(message);
                this.addAssistantMessage('', true);
            }
        }
    }

    handleMessage(data) {
        try {
            // 尝试解析 JSON
            const response = JSON.parse(data);
            
            if (response.type === 'code') {
                this.updateCode(response.data);
                this.finishStreaming();
            } else if (response.type === 'message') {
                this.updateLastAssistantMessage(response.content);
                this.finishStreaming();
            } else if (response.type === 'stream_start') {
                // 流式输出开始
                this.startStreaming();
            } else if (response.type === 'stream_chunk') {
                // 流式数据块
                this.appendStreamChunk(response.content);
            } else if (response.type === 'stream_end') {
                // 流式输出结束
                this.finishStreaming();
            } else if (response.type === 'error') {
                this.addSystemMessage(`❌ 错误: ${response.message}`);
                this.finishStreaming();
            }
        } catch (e) {
            // 非 JSON 格式，作为流式文本处理
            this.handleStreamingText(data);
        }
    }

    // 流式输出处理
    startStreaming() {
        this.isStreaming = true;
        this.streamBuffer = '';
        
        // 移除欢迎消息
        $('.welcome-message').fadeOut(300, function() { $(this).remove(); });
        
        // 确保有一个正在加载的助手消息
        const $lastMessage = $('#chatMessages .assistant-message').last();
        if (!$lastMessage.length || $lastMessage.attr('data-loading') !== 'true') {
            this.addAssistantMessage('', true);
        }
    }
    
    appendStreamChunk(chunk) {
        if (!this.isStreaming) {
            this.startStreaming();
        }
        
        // 添加到缓冲区
        this.streamBuffer += chunk;
        
        // 节流更新UI
        if (this.streamTimer) {
            clearTimeout(this.streamTimer);
        }
        
        this.streamTimer = setTimeout(() => {
            this.updateStreamingMessage();
        }, 50); // 50ms 节流
    }
    
    updateStreamingMessage() {
        const $lastMessage = $('#chatMessages .assistant-message').last();
        
        if ($lastMessage.length) {
            const formattedContent = this.formatMessage(this.streamBuffer);
            $lastMessage.removeClass('loading')
                      .addClass('streaming')
                      .attr('data-loading', 'false');
            $lastMessage.find('.message-text').html(formattedContent);
            
            // 提取并更新代码
            this.extractCodeFromStream(this.streamBuffer);
            
            this.scrollToBottom();
        }
    }
    
    extractCodeFromStream(content) {
        const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
        let match;
        let hasCode = false;
        
        while ((match = codeBlockRegex.exec(content)) !== null) {
            hasCode = true;
            const lang = match[1] ? match[1].toLowerCase() : 'html';
            const code = match[2].trim();
            
            if (lang === 'html' || lang === 'htm') {
                if (this.currentCode.html !== code) {
                    this.currentCode.html = code;
                    hasCode = true;
                }
            } else if (lang === 'css') {
                if (this.currentCode.css !== code) {
                    this.currentCode.css = code;
                    hasCode = true;
                }
            } else if (lang === 'javascript' || lang === 'js') {
                if (this.currentCode.js !== code) {
                    this.currentCode.js = code;
                    hasCode = true;
                }
            }
        }
        
        // 如果提取到代码，更新预览
        if (hasCode) {
            this.renderPreview();
        }
    }
    
    finishStreaming() {
        if (this.isStreaming) {
            this.isStreaming = false;
            
            if (this.streamTimer) {
                clearTimeout(this.streamTimer);
                this.streamTimer = null;
            }
            
            // 最后一次更新
            if (this.streamBuffer) {
                this.updateStreamingMessage();
            }
            
            // 移除流式输出样式
            const $lastMessage = $('#chatMessages .assistant-message').last();
            $lastMessage.removeClass('streaming');
            
            // AI生成完成后，延迟2秒自动刷新uniapp首页
            setTimeout(() => {
                this.refreshUniappHome();
            }, 2000);
        }
    }
    
    refreshUniappHome() {
        const $previewIframe = $('#previewContainer iframe');
        if ($previewIframe.length) {
            // 如果当前显示的是生成的代码预览，先显示一个提示
            this.addSystemMessage('✅ 应用已生成并添加到uniapp首页，正在刷新预览...');
            
            // 刷新uniapp首页iframe
            setTimeout(() => {
                // 创建手机外框
                const $phoneFrame = $('<div>', { class: 'phone-frame' });
                const $phoneScreen = $('<div>', { class: 'phone-screen' });
                
                const iframe = $('<iframe>', {
                    class: 'preview-iframe',
                    sandbox: 'allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-top-navigation',
                    frameborder: '0',
                    css: {
                        width: '100%',
                        height: '100%',
                        border: 'none',
                        display: 'block',
                        background: 'white'
                    }
                });
                iframe.attr('src', this.config.uniappHomeUrl + '?t=' + Date.now());
                
                // 组装手机框架结构
                $phoneScreen.append(iframe);
                $phoneFrame.append($phoneScreen);
                
                $('#previewContainer').empty().append($phoneFrame);
            }, 500);
        }
    }
    
    handleStreamingText(data) {
        // 处理纯文本流式输出（不带 JSON 包装）
        if (!this.isStreaming) {
            this.startStreaming();
        }
        
        this.appendStreamChunk(data);
    }

    // UI 消息显示
    addUserMessage(content) {
        $('.welcome-message').fadeOut(300, function() { $(this).remove(); });
        
        const messageHtml = `
            <div class="message user-message">
                <div class="message-avatar">
                    <i class="fas fa-user"></i>
                </div>
                <div class="message-content">
                    <div class="message-text">${this.escapeHtml(content)}</div>
                    <div class="message-time">${this.getCurrentTime()}</div>
                </div>
            </div>
        `;
        
        $('#chatMessages').append(messageHtml);
        this.scrollToBottom();
    }

    addAssistantMessage(content, isLoading = false) {
        const loadingClass = isLoading ? ' loading' : '';
        const loadingHtml = isLoading ? '<div class="typing-indicator"><span></span><span></span><span></span></div>' : '';
        
        const messageHtml = `
            <div class="message assistant-message${loadingClass}" data-loading="${isLoading}">
                <div class="message-avatar">
                    <i class="fas fa-robot"></i>
                </div>
                <div class="message-content">
                    <div class="message-text">${loadingHtml}${this.formatMessage(content)}</div>
                    <div class="message-time">${this.getCurrentTime()}</div>
                </div>
            </div>
        `;
        
        $('#chatMessages').append(messageHtml);
        this.scrollToBottom();
    }

    updateLastAssistantMessage(content) {
        const $lastMessage = $('#chatMessages .assistant-message').last();
        
        if ($lastMessage.length && $lastMessage.attr('data-loading') === 'true') {
            $lastMessage.removeClass('loading').attr('data-loading', 'false');
            $lastMessage.find('.message-text').html(this.formatMessage(content));
        } else {
            this.addAssistantMessage(content);
        }
        
        this.scrollToBottom();
    }

    addSystemMessage(content) {
        const messageHtml = `
            <div class="message system-message">
                <div class="message-content">
                    <div class="message-text">${this.escapeHtml(content)}</div>
                    <div class="message-time">${this.getCurrentTime()}</div>
                </div>
            </div>
        `;
        
        $('#chatMessages').append(messageHtml);
        this.scrollToBottom();
    }

    formatMessage(content) {
        if (!content) return '';
        
        // 转义 HTML
        let formatted = this.escapeHtml(content);
        
        // 代码块高亮
        formatted = formatted.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
            return `<div class="code-block"><div class="code-lang">${lang || 'code'}</div><pre><code>${code}</code></pre></div>`;
        });
        
        // 行内代码
        formatted = formatted.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');
        
        // 换行
        formatted = formatted.replace(/\n/g, '<br>');
        
        return formatted;
    }

    // 代码更新和预览
    updateCode(codeData) {
        if (codeData.html) this.currentCode.html = codeData.html;
        if (codeData.css) this.currentCode.css = codeData.css;
        if (codeData.js) this.currentCode.js = codeData.js;
        
        this.renderPreview();
    }

    renderPreview() {
        const $preview = $('#previewContainer');
        $('.empty-preview').fadeOut(300);
        
        // 构建完整的 HTML
        const fullHtml = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <style>
                    * { margin: 0; padding: 0; box-sizing: border-box; }
                    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
                    ${this.currentCode.css}
                </style>
            </head>
            <body>
                ${this.currentCode.html}
                <script>
                    try {
                        ${this.currentCode.js}
                    } catch(e) {
                        console.error('Script error:', e);
                    }
                </script>
            </body>
            </html>
        `;
        
        // 使用 iframe 隔离预览
        let $iframe = $preview.find('iframe');
        if (!$iframe.length) {
            $iframe = $('<iframe>', {
                class: 'preview-iframe',
                sandbox: 'allow-scripts allow-same-origin'
            });
            $preview.html($iframe);
        }
        
        const iframeDoc = $iframe[0].contentDocument || $iframe[0].contentWindow.document;
        iframeDoc.open();
        iframeDoc.write(fullHtml);
        iframeDoc.close();
        
        // 更新代码显示
        this.updateCodeDisplay();
        this.updateGenerationInfo();
    }

    updateCodeDisplay() {
        const currentLang = $('.code-tab.active').data('lang') || 'html';
        const code = this.currentCode[currentLang] || '';
        
        $('#codeContent').text(code);
    }

    updateGenerationInfo() {
        const totalLines = (this.currentCode.html.split('\n').length || 0) +
                          (this.currentCode.css.split('\n').length || 0) +
                          (this.currentCode.js.split('\n').length || 0);
        
        $('#codeSize').text(`${totalLines} 行`);
        $('#generationTime').text(this.getCurrentTime());
    }

    // 视图切换
    switchViewMode(btn) {
        $('.view-btn').removeClass('active');
        $(btn).addClass('active');
        
        const mode = $(btn).data('mode');
        const $previewContainer = $('#previewContainer');
        const $codeContainer = $('#codeContainer');
        
        if (mode === 'preview') {
            $previewContainer.show();
            $codeContainer.hide();
        } else if (mode === 'code') {
            $previewContainer.hide();
            $codeContainer.show();
        } else if (mode === 'split') {
            $previewContainer.css('width', '50%').show();
            $codeContainer.css('width', '50%').show();
        }
    }

    switchDevice(btn) {
        $('.device-btn').removeClass('active');
        $(btn).addClass('active');
        
        const device = $(btn).data('device');
        const $iframe = $('#previewContainer iframe');
        
        $iframe.removeClass('device-desktop device-tablet device-mobile');
        $iframe.addClass(`device-${device}`);
    }

    switchCodeTab(btn) {
        $('.code-tab').removeClass('active');
        $(btn).addClass('active');
        this.updateCodeDisplay();
    }

    // 导出功能
    exportChat() {
        const messages = [];
        $('#chatMessages .message').each(function() {
            const $msg = $(this);
            const type = $msg.hasClass('user-message') ? 'user' :
                        $msg.hasClass('assistant-message') ? 'assistant' : 'system';
            const content = $msg.find('.message-text').text();
            const time = $msg.find('.message-time').text();
            
            messages.push({ type, content, time });
        });
        
        const dataStr = JSON.stringify(messages, null, 2);
        this.downloadFile('chat-history.json', dataStr, 'application/json');
    }

    exportCode() {
        const zip = {
            'index.html': this.currentCode.html || '<!-- No HTML generated yet -->',
            'style.css': this.currentCode.css || '/* No CSS generated yet */',
            'script.js': this.currentCode.js || '// No JavaScript generated yet'
        };
        
        // 简化版：导出为单个 HTML 文件
        const fullHtml = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Generated App</title>
    <style>
${this.currentCode.css || '/* Add your styles here */'}
    </style>
</head>
<body>
${this.currentCode.html || '<!-- Add your content here -->'}
    <script>
${this.currentCode.js || '// Add your JavaScript here'}
    </script>
</body>
</html>`;
        
        this.downloadFile('generated-app.html', fullHtml, 'text/html');
    }

    copyCode() {
        const currentLang = $('.code-tab.active').data('lang') || 'html';
        const code = this.currentCode[currentLang] || '';
        
        if (!code) {
            alert('没有可复制的代码');
            return;
        }
        
        navigator.clipboard.writeText(code).then(() => {
            const $btn = $('#copyCodeBtn');
            const originalHtml = $btn.html();
            $btn.html('<i class="fas fa-check"></i>');
            setTimeout(() => $btn.html(originalHtml), 2000);
        }).catch(() => {
            alert('复制失败，请手动复制');
        });
    }

    downloadFile(filename, content, mimeType) {
        const blob = new Blob([content], { type: mimeType });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        URL.revokeObjectURL(url);
    }

    // 设置管理
    openSettings() {
        $('#settingsModal').fadeIn(300);
        $('#wsUrl').val(this.config.wsUrl);
        $('#reconnectInterval').val(this.config.reconnectInterval);
        $('#autoReconnect').prop('checked', this.config.autoReconnect);
    }

    closeSettings() {
        $('#settingsModal').fadeOut(300);
    }

    saveSettings() {
        this.config.wsUrl = $('#wsUrl').val().trim();
        this.config.reconnectInterval = parseInt($('#reconnectInterval').val());
        this.config.autoReconnect = $('#autoReconnect').is(':checked');
        
        localStorage.setItem('wsUrl', this.config.wsUrl);
        localStorage.setItem('reconnectInterval', this.config.reconnectInterval);
        localStorage.setItem('autoReconnect', this.config.autoReconnect);
        
        this.disconnect();
        this.closeSettings();
        
        if (this.config.autoReconnect) {
            this.connect();
        }
    }

    // 其他功能
    clearChat() {
        if (!confirm('确定要清空所有对话记录吗？')) return;
        
        $('#chatMessages').empty();
        this.currentCode = { html: '', css: '', js: '' };
        $('#previewContainer').html(`
            <div class="empty-preview">
                <div class="empty-icon">
                    <i class="fas fa-magic"></i>
                </div>
                <h3>等待生成内容</h3>
                <p>在左侧对话框中描述您的需求，AI将为您生成应用</p>
            </div>
        `);
    }

    initResizer() {
        const $resizer = $('#resizer');
        const $chatPanel = $('.chat-panel');
        const $previewPanel = $('.preview-panel');
        let isResizing = false;
        let startX = 0;
        let startWidth = 0;

        $resizer.on('mousedown', (e) => {
            isResizing = true;
            startX = e.pageX;
            startWidth = $chatPanel.width();
            $('body').css('cursor', 'ew-resize');
            e.preventDefault();
        });

        $(document).on('mousemove', (e) => {
            if (!isResizing) return;
            
            const delta = e.pageX - startX;
            const newWidth = startWidth + delta;
            const containerWidth = $('.main-content').width();
            const minWidth = 300;
            const maxWidth = containerWidth - minWidth - 10;
            
            if (newWidth >= minWidth && newWidth <= maxWidth) {
                $chatPanel.css('width', newWidth + 'px');
                $previewPanel.css('width', (containerWidth - newWidth - 10) + 'px');
            }
        });

        $(document).on('mouseup', () => {
            if (isResizing) {
                isResizing = false;
                $('body').css('cursor', '');
            }
        });
    }

    autoResizeTextarea(textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
    }

    updateSendButton() {
        const hasText = $('#messageInput').val().trim().length > 0;
        const isConnected = this.ws && this.ws.readyState === WebSocket.OPEN;
        $('#sendBtn').prop('disabled', !hasText);
    }

    scrollToBottom() {
        const $container = $('#chatMessages');
        $container.animate({ scrollTop: $container[0].scrollHeight }, 300);
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    getCurrentTime() {
        const now = new Date();
        return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    }
}

// 初始化应用
$(document).ready(() => {
    window.aiGenerator = new AIGenerator();
});
